<?php

App::uses('AppModel', 'Model');

/**
 * Project Model
 * 
 * PHP versions 5
 * CAKEPHP versions 2.x
 *
 * @author        TienVanVo <vantienvnn@gmail.com>
 * @link          
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 *
 */
class Reward extends AppModel {

	/**
	 * Validation rules.
	 *
	 * @var array
	 */
	public $validate = array(
		'name' => array(
			'notempty' => array(
				'allowEmpty' => false,
				'rule' => 'notempty',
				'message' => 'This name is required',
				'required' => true,
			),
			'minLength' => array(
				'allowEmpty' => false,
				'rule' => array('minLength', 3),
				'message' => 'Minimum 3 characters allowed',
			)
		),
		'percentage' => array(
			'notempty' => array(
				'required' => true,
				'allowEmpty' => false,
				'rule' => array('range', -0.1, 1),
				'message' => 'Please enter a number between 0.00 and 0.99'
			)
		),
		'weight' => array(
			'notempty' => array(
				'required' => true,
				'allowEmpty' => false,
				'rule' => 'numeric',
				'message' => 'Please supply the number of weight'
			)
		),
		'color' => array(
			'notempty' => array(
				'allowEmpty' => false,
				'rule' => 'alphaNumeric',
				'required' => true,
				'message' => 'Please supply the alpha numeric of color',
			),
			'between' => array(
				'allowEmpty' => false,
				'rule' => array('between', 6, 6),
				'message' => 'Hexa color is 6 characters'
			)
		)
	);

	public function generateValue() {
		$list = array();
		$rewards = $this->getRewards();
		$count = count($rewards);
		foreach (array_values($rewards) as $index => $reward) {
			$number = floor($reward['Reward']['percentage'] * $count * 10);
			for ($i = 0; $i < $number; $i++) {
				$list[] = $index + 1;
			}
		}
		shuffle($list);
		shuffle($list);
		$idx = mt_rand(0, count($list) - 1);
		return $list[$idx];
	}

	public function getRewards() {
		return $this->find('all', array('recursive' => -1, 'order' => 'weight'));
	}

	public function addTestData() {
		$segments = array(
			10, 15, 25, 30, 35, 50, 60, 75, 100, 200, 500, 1000, 1500, 2000
		);
		$percents = array(0.3, 0.2, 0.19, 0.18, 0.17, 0.15, 0.12, 0.10, 0.08, 0.06, 0.05, 0.03, 0.02, 0.02);
		$colors = array('#62c9f3', '#50bcd2', '#199e7f', '#139a68', '#0d793d', '#30a949', '#b5d133', '#d3e15b',
			'#f89c39', '#fbd517', '#f8ef21', '#f9ab1a', '#f89c39', '#ef7124', '#e74a27', '#cd202e');
		$idx = 1;
		foreach ($segments as $val) {
			$this->create();
			$this->save(array(
				'percentage' => next($percents),
				'color' => substr(next($colors), 1),
				'name' => "$val $",
				'weight' => $idx++
			));
		}
		exit();
	}

}

?>